<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 注意第二个参数 可以改变this指向
        var arr = [1, 2, 3, 4]
        var result = arr.filter(function (item, index, arr) {
            console.log(item, index, arr, this)
            return item % 2 === 0
        }, {})
        console.log(result)

        Array.prototype._filter = function (fn, context) {
            // this指向arr
            var arr = this
            var result = []
            if (typeof fn === 'function') {
                var _context = context || window
                for (var i = 0; i < arr.length; i++) {
                    var flag = fn.call(_context, arr[i], i, arr)
                    if (flag) result.push(arr[i])
                }
                return result
            } else {
                throw new Error('参数必须为函数')
            }
        }

        var result = arr._filter(function (item, index, arr) {
            console.log(item, index, arr, this)
            return item % 2 === 0
        }, {})
        console.log(result)

    </script>
</body>

</html>